package com.iteaj.iot.client.http;

import com.iteaj.iot.IotProtocolFactory;
import com.iteaj.iot.client.ClientComponent;
import com.iteaj.iot.client.ClientConnectProperties;
import com.iteaj.iot.client.IotClient;
import com.iteaj.iot.client.component.SimpleMultiClientManager;
import com.iteaj.iot.codec.filter.Interceptor;

public abstract class HttpClientComponent<M extends HttpClientMessage> extends SimpleMultiClientManager implements ClientComponent<M> {

    private boolean start;
    private long startTime;
    private HttpInterceptor interceptor;
    private HttpClientConnectProperties connectProperties;

    public HttpClientComponent() { }

    public HttpClientComponent(HttpClientConnectProperties connectProperties) {
        this(connectProperties, null);
    }

    public HttpClientComponent(HttpClientConnectProperties connectProperties, HttpInterceptor interceptor) {
        this.interceptor = interceptor;
        this.connectProperties = connectProperties;
    }

    @Override
    public boolean isStart() {
        return start;
    }

    @Override
    public long startTime() {
        return this.startTime;
    }

    @Override
    public void start(Object config) {
        this.start = true;
        this.startTime = System.currentTimeMillis();
    }

    @Override
    public void close() {
        this.start = false;
        this.clients().forEach(item -> {
            item.close();
        });
    }

    @Override
    public Interceptor getInterceptor() {
        return interceptor;
    }

    public void setInterceptor(HttpInterceptor interceptor) {
        this.interceptor = interceptor;
    }

    @Override
    public IotProtocolFactory protocolFactory() {
        return null;
    }

    @Override
    public HttpClientConnectProperties getConfig() {
        return this.connectProperties;
    }

    @Override
    public abstract HttpClient getClient();

    @Override
    public HttpClient getClient(Object clientKey) {
        return (HttpClient) super.getClient(clientKey);
    }

    @Override
    public synchronized HttpClient createNewClient(ClientConnectProperties config) {
        IotClient client = this.getClient(config);
        if(client == null) {
            client = doCreateClient(config);
            this.addClient(config, client);
        }

        return (HttpClient) client;
    }

    protected abstract HttpClient doCreateClient(ClientConnectProperties config);
}
